<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title></title>
	</head>
	<body>
		<canvas id="canvas"></canvas>
		<canvas id="canvas2"></canvas>
		<button id="output">输出</button>
		<script type="text/javascript">
			// 把颜色标记上，同时在另一张canvas将其他颜色画为透明
			const canvas = document.querySelector("#canvas");
			const ctx = canvas.getContext("2d");
			canvas.width = document.documentElement.clientWidth; //网页可见区域宽
			canvas.height = document.documentElement.clientHeight; //网页可见区域高
			
			const canvas2 = document.querySelector("#canvas2");
			const ctx2 = canvas2.getContext("2d");
			canvas2.width = canvas.width; //网页可见区域宽
			canvas2.height = canvas.height; //网页可见区域高
			
			// 容差
			const tolerance = 10; // prompt("请输入容差");
			const img = new Image();
			// 记录容差范围内的像素点
			const pixelPositions = [];
			
			img.src = "../image/bg.jpg";
			img.onload = () => {
				drawimg();
				// 先渲染上图片
				drawimg2();
			}
			function drawimg() {
				ctx.fillStyle = ctx.drawImage(img, 0, 0, canvas.width, canvas.height);
			}
			function drawimg2() {
				ctx2.fillStyle = ctx2.drawImage(img, 0, 0, canvas2.width, canvas2.height);
			}
			function absDiff(a, b) {
				return Math.abs(a - b) <= tolerance;
			}
			canvas.addEventListener("mousedown", (e) => {
				const [ x, y ] = [ e.offsetX, e.offsetY ];
				const [ r, g, b, a ] = ctx.getImageData(x, y, 1, 1).data;
				const imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
				const imageData2 = ctx.getImageData(0, 0, canvas2.width, canvas2.height);
				for (let i = 0; i < imageData.data.length; i += 4) {
					// 如果在容差范围内则替换为黑色
					if (absDiff(r, imageData.data[i]) 
						&& absDiff(g, imageData.data[i + 1]) 
						&& absDiff(b, imageData.data[i + 2])
						&& absDiff(a, imageData.data[i + 3])) {
						imageData.data[i] = 0;
						imageData.data[i + 1] = 0;
						imageData.data[i + 2] = 0;
						imageData.data[i + 3] = 255;
						// 如果有颜色记录像素点
						if(r != 0 || g != 0 || b != 0 ){
								let x = (i / 4) % canvas.width;
								let y = Math.floor((i / 4) / canvas.width);
								pixelPositions.push([x, y]);
						}
					} else {
						// 将没选中的像素去除
						imageData2.data[i] = 0;
						imageData2.data[i + 1] = 0;
						imageData2.data[i + 2] = 0;
						imageData2.data[i + 3] = 0;
					}
					
				}
				ctx.putImageData(imageData, 0, 0);
				ctx2.putImageData(imageData2, 0, 0);
			});
			// 输出选择的像素点
			output.onclick = () => {
				ctx2.clearRect(0, 0, canvas2.width, canvas2.height);
				pixelPositions.forEach(([x, y]) => {
					ctx2.fillRect(x, y, 1, 1);
				});
			}
			
		</script>
	</body>
</html>